package com.lmscn.lms.api.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.lmscn.lms.api.model.LoginCount;
import com.lmscn.lms.api.model.LoginLog;
import com.lmscn.lms.api.model.Student;
import com.lmscn.lms.api.model.SysProperties;
import com.lmscn.lms.api.model.SysUser;
import com.lmscn.lms.api.util.CommonUtil;
import com.lmscn.lms.api.util.DatahandleUtil;
import com.lmscn.lms.api.util.DesEncryptionUtil;
import com.lmscn.lms.api.util.JsonKit;
import com.lmscn.lms.api.util.PasswordEncoder;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Czl on 2015/7/24.
 * 
 * modified by zhang.xx 2016年11月10日10:39:23
 */
public class LoginController extends Controller {

	/**
	 * 用户登陆
	 *
	 * @date 2016年11月10日10:39:11
	 */
	public void userLogin() {
		Map<String, Object> dataMap = new HashMap<String, Object>();

		String username = getPara("username");
		String password = getPara("password");
//		String userType = getPara("userType");
		String uuid = getPara("UUID");
		
		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// System.out.println("接口开始时间：" + time.format(new Date()));

		// 不验证的用户列表
		SysProperties sysProperties = SysProperties.dao.findByName("verification_phone");
		String encodePassword = new PasswordEncoder().encode(password);
		SysUser sysUser = SysUser.dao.getLoginUser(username, encodePassword);

		Student student = null;
		if (sysProperties!=null && sysProperties.getStr("infor").contains(username)) {// 判断用户登录是否验证(不用验证)
			int num = (int) (Math.random() * 22) + 1;
			if (sysUser != null) {
//				student = Student.dao.findByUserId(sysUser.getLong("id"));
				long userId = sysUser.getLong("id");
				student = Student.dao.findByUserId(userId);
				
				student.set("post", DesEncryptionUtil.decryptStr(student.getStr("post")));
				if (student.get("little_img") == null || student.get("little_img").equals("")) {
					student.set("little_img", CommonUtil.getRandomHeadImgUrl(num));
				} else {
					student.set("little_img", CommonUtil.getHeadImgUrl(student));
				}
				if (student.get("organization") != null || student.get("organization") == "") {
					student.set("organization", "暂无");
				}
				dataMap.put("error_code", "0");
				dataMap.put("msg", "success");
				dataMap.put("sysUser", sysUser);
				dataMap.put("student", student);
			} else {
				dataMap.put("error_code", "1");
				dataMap.put("msg", "用户名或密码不正确!");
			}
			// System.out.println("接口无需校验的用户登录时间：" + time.format(new Date()));
		} else {
			if (uuid == null || uuid == "") {
				dataMap.put("error_code", "1");
				dataMap.put("msg", "验证失败！请更新版本！");
			} else {
				int num = (int) (Math.random() * 22) + 1;
				if (sysUser != null) {
//					student = Student.dao.findByUserId(sysUser.getLong("id"));
					long userId = sysUser.getLong("id");
					student = Student.dao.findByUserId(userId);
					if (student!=null) {
						student.set("post", DesEncryptionUtil.decryptStr(student.getStr("post")));
						if (student.get("little_img") == null || student.get("little_img").equals("")) {
							student.set("little_img", "http://120.77.0.245:9000/img/mr.png");
						} else {
							student.set("little_img", CommonUtil.getHeadImgUrl(student));
						}
						if (student.get("organization") != null || student.get("organization") == "") {
							student.set("organization", "暂无");
						}
						if (LoginCount.dao.findByUserName(username) == null) { // 第一次登陆t_login_count添加一条数据
							LoginCount.dao.save(new LoginCount(), uuid, username, sysUser.getLong("id"), new Date());
							
							// 记录登录日志 2017年3月23日15:36:10
//							LoginLog.dao.save(new LoginLog(), student.getStr("name"),username,student.getLong("id"),new Date());
							
							dataMap.put("error_code", "0");
							dataMap.put("msg", "success");
							dataMap.put("sysUser", sysUser);
							dataMap.put("student", student);
						} else {
							LoginCount.dao.save(new LoginCount(), uuid, username, sysUser.getLong("id"), new Date());
							
//							// 记录登录日志 2017年3月23日15:36:10
//							LoginLog.dao.save(new LoginLog(), student.getStr("name"),username,student.getLong("id"),new Date());
							
							dataMap.put("error_code", "0");
							dataMap.put("msg", "success");
							dataMap.put("sysUser", sysUser);
							dataMap.put("student", student);
							
//							if (LoginCount.dao.findByUserNameAndUUID(username, uuid) == null) {// 对比uuid，不同则不允许登录
//								dataMap.put("error_code", "1");
//								dataMap.put("msg", "请使用您的常用设备登录！");
//							} else {
//								
//
//							}
						}
					} else {
						dataMap.put("error_code", "1");
						dataMap.put("msg", "用户登录类型不匹配!");
					}
				} else {
					dataMap.put("error_code", "1");
					dataMap.put("msg", "用户名或密码不正确!");
				}
			}
			// System.out.println("接口需要校验的用户登录时间：" + time.format(new Date()));
		}

		// System.out.println("接口结束时间：" + time.format(new Date()));
		renderJson(JsonKit.mapToJson(dataMap, 100));
	}

	public void userType() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		String username = getPara("username");
		String password = getPara("password");
		Student student = null;
		
		// 不验证的用户列表
		String encodePassword = new PasswordEncoder().encode(password);
		SysUser sysUser = SysUser.dao.getLoginUser(username, encodePassword);
		if (sysUser != null) {
			long userId = sysUser.getLong("id");
			student = Student.dao.findByUserId(userId);
			if (student!=null) {
				dataMap.put("error_code", "0");
				dataMap.put("msg", "success");
				dataMap.put("userType", student.getStr("study_group"));
			} else {
				dataMap.put("error_code", "1");
				dataMap.put("msg", "登陆账号异常，请联系管理员!");
			}
		} else {
			dataMap.put("error_code", "1");
			dataMap.put("msg", "登陆账号异常，请联系管理员!");
		}
		
		renderJson(JsonKit.mapToJson(dataMap, 100));
	}
	
	
	/**
	 * 重置密码
	 * 
	 */
	public void resetPassword() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		String suserId = getPara("userId");
		String newPassword = getPara("newPassword");
		Long userId = Long.parseLong(suserId);
		int flag = SysUser.dao.resetPassword(userId, new PasswordEncoder().encode(newPassword));
		if (flag > 0) {
			dataMap.put("error_code", "0");
			dataMap.put("msg", "success");
		} else {
			dataMap.put("error_code", "1");
			dataMap.put("msg", "密码修改失败!");
		}
		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));

	}

	/**
	 * 上传头像
	 * 
	 * @date 2016年11月22日11:18:39
	 */
	public void uploadImage() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Long studentId = getParaToLong("studentId");
		Student student = Student.dao.findById(studentId);
		String headImg = getPara("headImg");
		// if (imgEncode(headImg, student)) {
		// 修改为上传到阿里云；
		// 修改为上传到共享；
		if (DatahandleUtil.imgEncode(headImg, student)) {
			dataMap.put("headUrl", CommonUtil.getHeadImgUrl(student));
			dataMap.put("msg", "上传成功");
			dataMap.put("error_code", "0");
		} else {
			dataMap.put("msg", "上传失败");
			dataMap.put("error_code", "1");
		}
		renderJson(JsonKit.mapToJson(dataMap, 39));
	}

	public static boolean imgEncode(String imgs, Student student) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(imgs);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成图片
			String imgFilePath = PathKit.getWebRootPath() + "/resources/upload/headImg/" + student.getStr("username") + ".png";// 新生成的图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			student.set("little_img", student.getStr("username") + ".png");
			student.update();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
